const express = require('express');
const cors = require('cors');
const axios = require('axios');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname)));

// 天气API配置
const WEATHER_API_KEY = process.env.WEATHER_API_KEY || 'YOUR_OPENWEATHER_API_KEY';
const WEATHER_API_URL = 'https://api.openweathermap.org/data/2.5/weather';

// 天气查询路由
app.get('/api/weather', async (req, res) => {
    try {
        const { city } = req.query;
        
        if (!city) {
            return res.status(400).json({ error: '请提供城市名称' });
        }

        const response = await axios.get(WEATHER_API_URL, {
            params: {
                q: city,
                appid: WEATHER_API_KEY,
                units: 'metric',
                lang: 'zh_cn'
            }
        });

        res.json(response.data);
    } catch (error) {
        console.error('天气API调用失败:', error.response?.data || error.message);
        
        if (error.response?.status === 404) {
            res.status(404).json({ error: '未找到该城市' });
        } else if (error.response?.status === 401) {
            res.status(401).json({ error: 'API密钥无效' });
        } else {
            res.status(500).json({ error: '获取天气信息失败' });
        }
    }
});

// 健康检查路由
app.get('/api/health', (req, res) => {
    res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// 提供静态文件服务
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'index.html'));
});

// 启动服务器
app.listen(PORT, () => {
    console.log(`天气查询服务已启动`);
    console.log(`本地访问: http://localhost:${PORT}`);
    console.log(`API文档: http://localhost:${PORT}/api/health`);
});

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({ error: '服务器内部错误' });
});

module.exports = app;